<?php

require_once dirname(__FILE__) . '/Config.php';
require_once dirname(__FILE__) . '/GaDataQuery.php';
require_once dirname(__FILE__) . '/Models/Model.php';
require_once dirname(__FILE__) . '/Models/Token.php';
require_once dirname(__FILE__) . '/google-api-php-client/src/Google_Client.php';
require_once dirname(__FILE__) . '/google-api-php-client/src/contrib/Google_AnalyticsService.php';

/**
 * @author HungNQ
 */
class GaFetcherNotProvided
{

    private $google_service;
    private $google_client;
    public $application_name;
    public $client_id;
    public $client_secret;
    public $redirect_uri;
    public $developer_key;
    public $access_type;

    public function getData()
    {
        $token = $this->google_client->getAccessToken();
        $authObj = json_decode($token);

        $refreshToken = '';

        if (isset($authObj->refresh_token)) {
            $refreshToken = $authObj->refresh_token;
        }

        $tokenObj = new Token();

        if (strlen($refreshToken)) {
            $tokenObj->token = $refreshToken;
            $tokenObj->type = Token::TYPE_REFRESH;
            $tokenObj->save();
            $this->google_client->refreshToken($refreshToken);
        }
        $_SESSION['token'] = $this->google_client->getAccessToken();

        $today = strtotime("today 00:00");
        $yesterday = strtotime("-1 day", $today);

        $from = date('Y-m-d', $yesterday); // -1 days
        $to = date('Y-m-d', $today);

        $optDimensions = array(
            GaDataQuery::DIMENSION_LANDING_PAGE_PATH,
            GaDataQuery::DIMENSION_PAGE_TITLE,
        );

        $optMetrics = array(
            GaDataQuery::METRIC_BOUNCES,
            GaDataQuery::METRIC_PAGEVIEWS
        );

        $metrics = implode(",", $optMetrics);
        $dimensions = implode(",", $optDimensions);

        //$metrics = 'ga:visits,ga:pageviewsPerVisit,ga:pageviews,ga:avgTimeOnPage,ga:bounces,ga:timeOnPage,ga:bounces,ga:visitors,ga:pageviews';
        //$dimensions = 'ga:landingPagePath,ga:pageTitle,ga:date,ga:year,ga:month,ga:day';

        $optParams = array(
            'dimensions' => $dimensions,
            'sort' => '-ga:pageviews',
            'filters' => 'ga:keyword==(not provided)',
            'max-results' => MAX_RESULT,
        );
        //$from = '2013-05-07';
        //$to = '2013-05-08';

        $data = $this->google_service->data_ga->get("ga:31405012", $from, $to, $metrics, $optParams);
        $this->printData($data);
        $this->insertData($data);
        return $data;
    }

    public function insertData($data)
    {
        $model = new Model();
        $sql = "INSERT INTO notprovided (landing_page, page_title, bounces, pageviews) VALUES";
        //$values = array_fill(0, count($data['rows']), " (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        //$sql .= implode(",", $values);
        $model->insertNotProvided($sql, $data);
    }

    public function printData($data)
    {
        if (DATA_INDEX_SHOW) {
            $_params[] = 'landing page';
            $_params[] = 'title';
            // metrics
            $_params[] = 'date';
            $_params[] = 'date_year';
            $_params[] = 'date_month';
            //$_params[] = 'hour';
            // dimensions

            $_params[] = 'visits';
            $_params[] = 'pageviews_per_visit';
            $_params[] = 'time_on_page';
            $_params[] = 'avg_time_on_page';
            $_params[] = 'bounce_rate';
            $_params[] = 'visitors';
            $_params[] = 'pageviews';

            echo "<table border=1>\n";
            foreach ($_params as $index => $column) {
                echo "\t<th>$column</th>\n";
            }
            foreach ($data['rows'] as $row) {
                echo "\t<tr>\n";
                foreach ($_params as $index => $colmn) {//
                    echo "\t\t<td>$row[$index]</td>\n";
                }
                echo "\t</tr>\n";
            }
            echo "</table>\n";
        }
    }

    public function getGoogleClient()
    {
        if (is_null($this->google_client)) {
            $this->google_client = new Google_Client();
            $this->google_client->setApplicationName($this->application_name);
            $this->google_client->setClientId($this->client_id);
            $this->google_client->setClientSecret($this->client_secret);
            $this->google_client->setRedirectUri($this->redirect_uri);
            $this->google_client->setDeveloperKey($this->developer_key);
            $this->google_client->setAccessType($this->access_type); //important
        }
        return $this->google_client;
    }

    public function getGoogleService()
    {
        if (is_null($this->google_service)) {
            $google_client = $this->getGoogleClient();
            $this->google_service = new Google_AnalyticsService($google_client);
        }
        return $this->google_service;
    }

    public function getRefeshToken()
    {
        $tokenObj = new Token();

        $token = $tokenObj->getTokenByType('refresh');

        return $token;
    }

}
